// MongoDB初始化脚本
db = db.getSiblingDB('gof23-game');

// 创建用户 (如果不存在)
const userExists = db.getUser('gof23user');
if (!userExists) {
  db.createUser({
    user: 'gof23user',
    pwd: 'gof23password',
    roles: [
      { role: 'readWrite', db: 'gof23-game' }
    ]
  });
  print('User "gof23user" created.');
} else {
  print('User "gof23user" already exists.');
}


// --- 设计模式数据 ---
const patterns = [
  // --- Creational Patterns ---
  {
    name: 'Abstract Factory',
    category: 'Creational',
    description: 'Provides an interface for creating families of related or dependent objects without specifying their concrete classes.',
    intent: 'Provide an interface for creating families of related or dependent objects without specifying their concrete classes.',
    applicability: 'Use when a system should be independent of how its products are created, composed, and represented.',
    structure: 'Defines an abstract factory interface for creating abstract products and concrete factories that produce concrete products.',
    participants: 'AbstractFactory, ConcreteFactory, AbstractProduct, ConcreteProduct, Client.',
    collaborations: 'The client uses the abstract factory to create products, remaining unaware of the concrete classes.',
    consequences: 'Isolates concrete classes, makes exchanging product families easy, promotes consistency among products.',
    implementation: 'Typically implemented with a factory for each product family.',
    knownUses: 'UI toolkits for creating widgets across different look-and-feels (e.g., Motif, Presentation Manager).',
    relatedPatterns: ['Factory Method', 'Singleton', 'Prototype'],
    sampleCode: `/**
 * 抽象工厂模式示例
 * 提供一个创建一系列相关或相互依赖对象的接口，而无需指定它们具体的类
 */

// 抽象产品A
interface AbstractProductA {
  operationA(): string;
}

// 抽象产品B
interface AbstractProductB {
  operationB(): string;
  collaborateWith(productA: AbstractProductA): string;
}

// 具体产品A1
class ConcreteProductA1 implements AbstractProductA {
  public operationA(): string {
    return '产品A1的结果';
  }
}

// 具体产品A2
class ConcreteProductA2 implements AbstractProductA {
  public operationA(): string {
    return '产品A2的结果';
  }
}

// 具体产品B1
class ConcreteProductB1 implements AbstractProductB {
  public operationB(): string {
    return '产品B1的结果';
  }

  public collaborateWith(productA: AbstractProductA): string {
    const result = productA.operationA();
    return \`产品B1与\${result}协作\`;
  }
}

// 具体产品B2
class ConcreteProductB2 implements AbstractProductB {
  public operationB(): string {
    return '产品B2的结果';
  }

  public collaborateWith(productA: AbstractProductA): string {
    const result = productA.operationA();
    return \`产品B2与\${result}协作\`;
  }
}

// 抽象工厂
interface AbstractFactory {
  createProductA(): AbstractProductA;
  createProductB(): AbstractProductB;
}

// 具体工厂1 - 创建产品A1和B1
class ConcreteFactory1 implements AbstractFactory {
  public createProductA(): AbstractProductA {
    return new ConcreteProductA1();
  }

  public createProductB(): AbstractProductB {
    return new ConcreteProductB1();
  }
}

// 具体工厂2 - 创建产品A2和B2
class ConcreteFactory2 implements AbstractFactory {
  public createProductA(): AbstractProductA {
    return new ConcreteProductA2();
  }

  public createProductB(): AbstractProductB {
    return new ConcreteProductB2();
  }
}

// 客户端代码
function clientCode(factory: AbstractFactory) {
  const productA = factory.createProductA();
  const productB = factory.createProductB();

  console.log(productB.operationB());
  console.log(productB.collaborateWith(productA));
}

// 应用程序根据配置或环境选择工厂类型
console.log('客户端使用第一个工厂类型:');
clientCode(new ConcreteFactory1());

console.log('');

console.log('客户端使用第二个工厂类型:');
clientCode(new ConcreteFactory2());`
  },
  {
    name: 'Builder',
    category: 'Creational',
    description: 'Separates the construction of a complex object from its representation, allowing the same construction process to create different representations.',
    intent: 'Separate the construction of a complex object from its representation so that the same construction process can create different representations.',
    applicability: 'Use when the algorithm for creating a complex object should be independent of the parts that make up the object and how they\'re assembled.',
    structure: 'A Director requests the construction of a product from a Builder, which constructs the product step by step.',
    participants: 'Builder, ConcreteBuilder, Director, Product.',
    collaborations: 'The Director instructs the Builder on how to construct the product. The Builder builds the product and provides it to the client.',
    consequences: 'Lets you vary a product\'s internal representation, isolates code for construction and representation, gives you finer control over the construction process.',
    implementation: 'Define a Builder interface for creating parts of a Product object. The Director controls the construction algorithm.',
    knownUses: 'RTF document converters, building complex objects like cars or houses.',
    relatedPatterns: ['Abstract Factory', 'Composite'],
    sampleCode: `/**
 * 建造者模式示例
 * 将一个复杂对象的构建与它的表示分离，使得同样的构建过程可以创建不同的表示
 */

// 产品类
class Product {
  private parts: string[] = [];

  public addPart(part: string): void {
    this.parts.push(part);
  }

  public listParts(): string {
    return \`产品组件: \${this.parts.join(', ')}\`;
  }
}

// 抽象建造者
interface Builder {
  reset(): void;
  buildPartA(): void;
  buildPartB(): void;
  buildPartC(): void;
}

// 具体建造者1
class ConcreteBuilder1 implements Builder {
  private product: Product;

  constructor() {
    this.reset();
  }

  public reset(): void {
    this.product = new Product();
  }

  public buildPartA(): void {
    this.product.addPart("部件A1");
  }

  public buildPartB(): void {
    this.product.addPart("部件B1");
  }

  public buildPartC(): void {
    this.product.addPart("部件C1");
  }

  // 具体建造者应该提供获取结果的方法
  public getProduct(): Product {
    const result = this.product;
    this.reset();
    return result;
  }
}

// 具体建造者2
class ConcreteBuilder2 implements Builder {
  private product: Product;

  constructor() {
    this.reset();
  }

  public reset(): void {
    this.product = new Product();
  }

  public buildPartA(): void {
    this.product.addPart("部件A2");
  }

  public buildPartB(): void {
    this.product.addPart("部件B2");
  }

  public buildPartC(): void {
    this.product.addPart("部件C2");
  }

  public getProduct(): Product {
    const result = this.product;
    this.reset();
    return result;
  }
}

// 指挥者类
class Director {
  private builder: Builder;

  public setBuilder(builder: Builder): void {
    this.builder = builder;
  }

  // 指挥者知道建造产品的具体步骤
  public buildMinimalViableProduct(): void {
    this.builder.buildPartA();
  }

  public buildFullFeaturedProduct(): void {
    this.builder.buildPartA();
    this.builder.buildPartB();
    this.builder.buildPartC();
  }
}

// 客户端代码
function clientCode(director: Director) {
  const builder1 = new ConcreteBuilder1();
  director.setBuilder(builder1);

  console.log('标准基础产品:');
  director.buildMinimalViableProduct();
  console.log(builder1.getProduct().listParts());

  console.log('标准完整产品:');
  director.buildFullFeaturedProduct();
  console.log(builder1.getProduct().listParts());

  // 记住，建造者模式也可以不使用指挥者类
  console.log('自定义产品:');
  builder1.buildPartA();
  builder1.buildPartC();
  console.log(builder1.getProduct().listParts());

  const builder2 = new ConcreteBuilder2();
  director.setBuilder(builder2);
  
  console.log('另一个类型的标准完整产品:');
  director.buildFullFeaturedProduct();
  console.log(builder2.getProduct().listParts());
}

// 使用示例
const director = new Director();
clientCode(director);`
  },
  {
    name: 'Factory Method',
    category: 'Creational',
    description: 'Defines an interface for creating an object, but lets subclasses decide which class to instantiate.',
    intent: 'Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.',
    applicability: 'Use when a class can\'t anticipate the class of objects it must create or wants its subclasses to specify the objects it creates.',
    structure: 'A Creator defines a factory method, and ConcreteCreators override it to produce specific products.',
    participants: 'Product, ConcreteProduct, Creator, ConcreteCreator.',
    collaborations: 'The Creator relies on its subclasses to implement the factory method.',
    consequences: 'Provides hooks for subclasses, connects parallel class hierarchies.',
    implementation: 'An abstract Creator defines an abstract factory method that ConcreteCreators implement.',
    knownUses: 'Document frameworks, toolkits.',
    relatedPatterns: ['Abstract Factory', 'Template Method', 'Prototype'],
    sampleCode: `/**
 * 工厂方法模式示例
 * 定义一个用于创建对象的接口，让子类决定实例化哪个类
 */

// 产品接口
interface Product {
  operation(): string;
}

// 具体产品A
class ConcreteProductA implements Product {
  public operation(): string {
    return '具体产品A的结果';
  }
}

// 具体产品B
class ConcreteProductB implements Product {
  public operation(): string {
    return '具体产品B的结果';
  }
}

// 创建者抽象类
abstract class Creator {
  // 工厂方法
  public abstract factoryMethod(): Product;

  // 使用产品的业务逻辑
  public someOperation(): string {
    // 调用工厂方法创建产品
    const product = this.factoryMethod();
    // 使用产品
    return \`创建者: 工厂方法创建了 \${product.operation()}\`;
  }
}

// 具体创建者A - 创建产品A
class ConcreteCreatorA extends Creator {
  public factoryMethod(): Product {
    return new ConcreteProductA();
  }
}

// 具体创建者B - 创建产品B
class ConcreteCreatorB extends Creator {
  public factoryMethod(): Product {
    return new ConcreteProductB();
  }
}

// 客户端代码
function clientCode(creator: Creator) {
  console.log('客户端代码与创建者一起工作...');
  console.log(creator.someOperation());
}

// 应用程序选择创建者类型
console.log('使用具体创建者A:');
clientCode(new ConcreteCreatorA());
console.log('');

console.log('使用具体创建者B:');
clientCode(new ConcreteCreatorB());`
  },
  {
    name: 'Prototype',
    category: 'Creational',
    description: 'Specifies the kinds of objects to create using a prototypical instance, and creates new objects by copying this prototype.',
    intent: 'Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.',
    applicability: 'Use when a system should be independent of how its products are created, composed, and represented; and when the classes to instantiate are specified at run-time.',
    structure: 'A Client asks a Prototype to clone itself.',
    participants: 'Prototype, ConcretePrototype, Client.',
    collaborations: 'A client asks a prototype to clone itself.',
    consequences: 'Hiding the concrete product classes from the client, adding and removing products at run-time, specifying new objects by varying values.',
    implementation: 'Implement a cloning operation in the Prototype interface.',
    knownUses: 'Creating complex objects that are expensive to create from scratch.',
    relatedPatterns: ['Abstract Factory', 'Composite', 'Decorator'],
    sampleCode: `/**
 * 原型模式示例
 * 用原型实例指定创建对象的种类，并且通过拷贝这些原型创建新的对象
 */

// 原型接口
interface Prototype {
  clone(): Prototype;
}

// 具体原型1
class ConcretePrototype1 implements Prototype {
  public primitive: any;
  public component: object;
  public circularReference: ComponentWithBackReference;

  public clone(): this {
    const clone = Object.create(this);
    
    // 克隆原始字段值（已经包含在对象中）
    
    // 克隆对象字段
    clone.component = Object.create(this.component);
    
    // 克隆具有反向引用的对象
    clone.circularReference = {
      ...this.circularReference,
      prototype: { ...this }
    };
    
    return clone;
  }
}

// 具有反向引用的组件
class ComponentWithBackReference {
  public prototype;
  
  constructor(prototype: Prototype) {
    this.prototype = prototype;
  }
}

// 具体原型2
class ConcretePrototype2 implements Prototype {
  private field1: string;
  private field2: number;
  
  constructor(field1: string, field2: number) {
    this.field1 = field1;
    this.field2 = field2;
  }
  
  public clone(): this {
    // 创建一个新对象并复制当前实例的属性
    const clone = Object.create(this);
    clone.field1 = this.field1;
    clone.field2 = this.field2;
    return clone;
  }
  
  public getDetails(): string {
    return \`字段1: \${this.field1}, 字段2: \${this.field2}\`;
  }
}

// 客户端代码
function clientCode() {
  // 使用示例1：复杂对象克隆
  const p1 = new ConcretePrototype1();
  p1.primitive = 245;
  p1.component = new Date();
  p1.circularReference = new ComponentWithBackReference(p1);
  
  const p1Clone = p1.clone();
  
  console.log('原始对象的循环引用原型与原型对象相同吗？', 
               p1.circularReference.prototype === p1);
  console.log('克隆对象的循环引用原型与克隆对象相同吗？', 
               p1Clone.circularReference.prototype === p1Clone);
  
  // 使用示例2：简单对象克隆
  const p2 = new ConcretePrototype2("测试", 100);
  console.log('原型2详情:', p2.getDetails());
  
  const p2Clone = p2.clone();
  console.log('克隆的原型2详情:', p2Clone.getDetails());
}

// 执行客户端代码
clientCode();`
  },
  {
    name: 'Singleton',
    category: 'Creational',
    description: 'Ensures a class has only one instance and provides a global point of access to it.',
    intent: 'Ensure a class only has one instance, and provide a global point of access to it.',
    applicability: 'Use the Singleton pattern when there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.',
    structure: 'The Singleton class declares the static method getInstance() that returns the same instance of its own class.',
    participants: 'Singleton',
    collaborations: 'Clients access a Singleton instance solely through the Singleton\'s getInstance() method.',
    consequences: 'Controlled access to sole instance, reduced namespace, permits refinement of operations and representation.',
    implementation: 'A static method controls the single instance, often with a private constructor.',
    knownUses: 'Logging classes, database connection managers, configuration settings.',
    relatedPatterns: ['Abstract Factory', 'Builder', 'Prototype'],
    sampleCode: `/**
 * 单例模式示例
 * 确保一个类只有一个实例，并提供一个全局访问点
 */
class Singleton {
  private static instance: Singleton;
  
  // 私有构造函数，防止通过 new 创建实例
  private constructor() {
    console.log('单例实例已创建');
  }
  
  // 提供访问单例实例的静态方法
  public static getInstance(): Singleton {
    if (!Singleton.instance) {
      Singleton.instance = new Singleton();
    }
    return Singleton.instance;
  }
  
  // 业务方法
  public someBusinessLogic() {
    console.log('执行业务逻辑');
    return '单例实例的结果';
  }
}

// 使用示例
function clientCode() {
  // 不可以使用 new 操作符
  // const singleton = new Singleton(); // 这会报错

  // 获取单例实例
  const singleton1 = Singleton.getInstance();
  const singleton2 = Singleton.getInstance();

  // 验证得到的是同一个实例
  if (singleton1 === singleton2) {
    console.log('单例有效：两个变量包含相同的实例。');
  } else {
    console.log('单例失败：两个变量包含不同的实例。');
  }

  // 使用单例
  singleton1.someBusinessLogic();
}

// 执行客户端代码
clientCode();`
  },
  // --- Structural Patterns ---
  {
    name: 'Adapter',
    category: 'Structural',
    description: 'Converts the interface of a class into another interface clients expect.',
    intent: 'Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn\'t otherwise because of incompatible interfaces.',
    applicability: 'Use when you want to use an existing class, and its interface does not match the one you need.',
    structure: 'An Adapter implements the Target interface and delegates calls to an Adaptee object.',
    participants: 'Target, Client, Adapter, Adaptee.',
    collaborations: 'The client calls the Adapter, which in turn calls the Adaptee.',
    consequences: 'Allows two incompatible interfaces to work together.',
    implementation: 'Class adapters use multiple inheritance, while object adapters use composition.',
    knownUses: 'Wrapping existing libraries or legacy code.',
    relatedPatterns: ['Bridge', 'Decorator', 'Proxy'],
    sampleCode: `/**
 * 适配器模式示例
 * 将一个类的接口转换成客户希望的另外一个接口
 */

// 目标接口
interface Target {
  request(): string;
}

// 需要适配的类
class Adaptee {
  public specificRequest(): string {
    return '这是适配者的特殊请求。';
  }
}

// 对象适配器（使用组合）
class ObjectAdapter implements Target {
  private adaptee: Adaptee;
  
  constructor(adaptee: Adaptee) {
    this.adaptee = adaptee;
  }
  
  public request(): string {
    const result = this.adaptee.specificRequest();
    return \`适配器：(转换) ${result.split('').reverse().join('')}\`;
  }
}

// 类适配器（使用继承）- 注意：TypeScript不支持多重继承，这里模拟展示
class ClassAdapter implements Target {
  // 这里我们不能直接从Adaptee继承，所以创建一个私有实例
  private adaptee = new Adaptee();
  
  public request(): string {
    const result = this.adaptee.specificRequest();
    return \`适配器：(转换) ${result.split('').reverse().join('')}\`;
  }
}

// 客户端代码
function clientCode(target: Target) {
  console.log(target.request());
}

// 使用示例
console.log('客户端可以正常使用Target接口:');
const target = {
  request(): string {
    return '目标：默认目标行为。';
  }
};
clientCode(target);

console.log('');

const adaptee = new Adaptee();
console.log('适配者接口不兼容客户端:');
console.log(\`适配者: \${adaptee.specificRequest()}\`);

console.log('');

console.log('客户端可以通过对象适配器使用适配者:');
const objectAdapter = new ObjectAdapter(adaptee);
clientCode(objectAdapter);

console.log('');

console.log('客户端可以通过类适配器使用适配者:');
const classAdapter = new ClassAdapter();
clientCode(classAdapter);`
  },
  {
    name: 'Bridge',
    category: 'Structural',
    description: 'Decouples an abstraction from its implementation so that the two can vary independently.',
    intent: 'Decouple an abstraction from its implementation so that the two can vary independently.',
    applicability: 'Use when you want to avoid a permanent binding between an abstraction and its implementation, and when both the abstraction and its implementation can have their own subclass hierarchies.',
    structure: 'An Abstraction forwards client requests to its Implementor.',
    participants: 'Abstraction, RefinedAbstraction, Implementor, ConcreteImplementor.',
    collaborations: 'The Abstraction forwards client requests to its Implementor object.',
    consequences: 'Decoupling interface and implementation, improved extensibility.',
    implementation: 'The Abstraction holds a reference to an Implementor.',
    knownUses: 'GUI frameworks, device drivers.',
    relatedPatterns: ['Abstract Factory', 'Adapter'],
    sampleCode: `/**
 * 桥接模式示例
 * 将抽象部分与它的实现部分分离，使它们都可以独立地变化
 */

// 实现部分的接口
interface Implementation {
  operationImplementation(): string;
}

// 具体实现A
class ConcreteImplementationA implements Implementation {
  public operationImplementation(): string {
    return "具体实现A的结果";
  }
}

// 具体实现B
class ConcreteImplementationB implements Implementation {
  public operationImplementation(): string {
    return "具体实现B的结果";
  }
}

// 抽象部分
class Abstraction {
  protected implementation: Implementation;

  constructor(implementation: Implementation) {
    this.implementation = implementation;
  }

  public operation(): string {
    const result = this.implementation.operationImplementation();
    return \`抽象：基础操作与 \${result}\`;
  }
}

// 扩展的抽象
class ExtendedAbstraction extends Abstraction {
  public operation(): string {
    const result = this.implementation.operationImplementation();
    return \`扩展抽象：扩展操作与 \${result}\`;
  }
}

// 客户端代码
function clientCode(abstraction: Abstraction) {
  console.log(abstraction.operation());
}

// 使用示例
let implementation = new ConcreteImplementationA();
let abstraction = new Abstraction(implementation);
clientCode(abstraction);

console.log("");

implementation = new ConcreteImplementationB();
abstraction = new ExtendedAbstraction(implementation);
clientCode(abstraction);

// 更实际的例子：遥控器（抽象）和设备（实现）
interface Device {
  isEnabled(): boolean;
  enable(): void;
  disable(): void;
  getVolume(): number;
  setVolume(percent: number): void;
  getChannel(): number;
  setChannel(channel: number): void;
}

// 具体设备：电视
class TV implements Device {
  private on: boolean = false;
  private volume: number = 30;
  private channel: number = 1;

  public isEnabled(): boolean {
    return this.on;
  }

  public enable(): void {
    this.on = true;
  }

  public disable(): void {
    this.on = false;
  }

  public getVolume(): number {
    return this.volume;
  }

  public setVolume(percent: number): void {
    if (percent > 100) {
      this.volume = 100;
    } else if (percent < 0) {
      this.volume = 0;
    } else {
      this.volume = percent;
    }
  }

  public getChannel(): number {
    return this.channel;
  }

  public setChannel(channel: number): void {
    this.channel = channel;
  }
}

// 具体设备：收音机
class Radio implements Device {
  private on: boolean = false;
  private volume: number = 20;
  private channel: number = 88.5;

  public isEnabled(): boolean {
    return this.on;
  }

  public enable(): void {
    this.on = true;
  }

  public disable(): void {
    this.on = false;
  }

  public getVolume(): number {
    return this.volume;
  }

  public setVolume(percent: number): void {
    if (percent > 100) {
      this.volume = 100;
    } else if (percent < 0) {
      this.volume = 0;
    } else {
      this.volume = percent;
    }
  }

  public getChannel(): number {
    return this.channel;
  }

  public setChannel(channel: number): void {
    this.channel = channel;
  }
}

// 遥控器抽象类
class RemoteControl {
  protected device: Device;

  constructor(device: Device) {
    this.device = device;
  }

  public togglePower(): void {
    if (this.device.isEnabled()) {
      this.device.disable();
      console.log("电源关闭");
    } else {
      this.device.enable();
      console.log("电源开启");
    }
  }

  public volumeDown(): void {
    const currentVolume = this.device.getVolume();
    this.device.setVolume(currentVolume - 10);
    console.log(\`音量: \${this.device.getVolume()}%\`);
  }

  public volumeUp(): void {
    const currentVolume = this.device.getVolume();
    this.device.setVolume(currentVolume + 10);
    console.log(\`音量: \${this.device.getVolume()}%\`);
  }

  public channelDown(): void {
    const currentChannel = this.device.getChannel();
    this.device.setChannel(currentChannel - 1);
    console.log(\`频道: \${this.device.getChannel()}\`);
  }

  public channelUp(): void {
    const currentChannel = this.device.getChannel();
    this.device.setChannel(currentChannel + 1);
    console.log(\`频道: \${this.device.getChannel()}\`);
  }
}

// 高级遥控器
class AdvancedRemoteControl extends RemoteControl {
  public mute(): void {
    this.device.setVolume(0);
    console.log("静音");
  }
}

// 使用桥接模式的客户端代码
function testRemote() {
  const tv = new TV();
  const remote = new RemoteControl(tv);
  
  remote.togglePower();
  remote.volumeUp();
  remote.channelUp();
  remote.channelUp();
  
  const radio = new Radio();
  const advancedRemote = new AdvancedRemoteControl(radio);
  
  advancedRemote.togglePower();
  advancedRemote.volumeUp();
  advancedRemote.volumeUp();
  advancedRemote.mute();
}

// 测试遥控器和设备
console.log("测试遥控器：");
testRemote();`
  },
  {
    name: 'Composite',
    category: 'Structural',
    description: 'Composes objects into tree structures to represent part-whole hierarchies.',
    intent: 'Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.',
    applicability: 'Use when you want to represent part-whole hierarchies of objects and want to be able to treat individual objects and compositions of objects in a uniform way.',
    structure: 'A Component defines an interface for both Leaf and Composite objects.',
    participants: 'Component, Leaf, Composite, Client.',
    collaborations: 'The client interacts with the Component interface, treating Leafs and Composites uniformly.',
    consequences: 'Makes it easy to add new kinds of components, simplifies client code.',
    implementation: 'Define an interface for all objects in the composition, both the composite and the leaf nodes.',
    knownUses: 'File systems, GUI toolkits.',
    relatedPatterns: ['Decorator', 'Flyweight', 'Iterator', 'Visitor'],
    sampleCode: '...'
  },
  {
    name: 'Decorator',
    category: 'Structural',
    description: 'Attaches additional responsibilities to an object dynamically.',
    intent: 'Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.',
    applicability: 'Use for adding responsibilities to individual objects dynamically and transparently, without affecting other objects.',
    structure: 'A Decorator wraps a Component and conforms to its interface.',
    participants: 'Component, ConcreteComponent, Decorator, ConcreteDecorator.',
    collaborations: 'A Decorator forwards requests to its Component object and may optionally perform additional operations before or after forwarding.',
    consequences: 'More flexibility than static inheritance, avoids feature-laden classes high up in the hierarchy.',
    implementation: 'A Decorator conforms to the interface of the Component it decorates.',
    knownUses: 'Adding borders or scrolling to UI components, I/O streams in Java.',
    relatedPatterns: ['Adapter', 'Composite', 'Strategy'],
    sampleCode: '...'
  },
  {
    name: 'Facade',
    category: 'Structural',
    description: 'Provides a unified interface to a set of interfaces in a subsystem.',
    intent: 'Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.',
    applicability: 'Use when you want to provide a simple interface to a complex subsystem, or when you want to decouple a subsystem from its clients.',
    structure: 'A Facade knows which subsystem classes are responsible for a request.',
    participants: 'Facade, Subsystem classes.',
    collaborations: 'Clients communicate with the subsystem by sending requests to the Facade.',
    consequences: 'Shields clients from subsystem components, promotes weak coupling.',
    implementation: 'Identify the common tasks and entry points of the subsystem and create a Facade class that delegates to the appropriate subsystem classes.',
    knownUses: 'Compiler architectures, simplifying complex APIs.',
    relatedPatterns: ['Abstract Factory', 'Mediator'],
    sampleCode: '...'
  },
  {
    name: 'Flyweight',
    category: 'Structural',
    description: 'Uses sharing to support large numbers of fine-grained objects efficiently.',
    intent: 'Use sharing to support large numbers of fine-grained objects efficiently.',
    applicability: 'Use when an application uses a large number of objects, and these objects can be managed by sharing.',
    structure: 'A FlyweightFactory creates and manages flyweight objects. Clients request flyweights from the factory.',
    participants: 'Flyweight, ConcreteFlyweight, UnsharedConcreteFlyweight, FlyweightFactory, Client.',
    collaborations: 'Clients request a flyweight from the factory and pass it extrinsic state.',
    consequences: 'Reduction in the total number of objects, centralization of state for many virtual objects.',
    implementation: 'Flyweights are shared; their extrinsic state is passed in by clients.',
    knownUses: 'Character representations in text editors, graphical elements.',
    relatedPatterns: ['Composite', 'State', 'Strategy'],
    sampleCode: '...'
  },
  {
    name: 'Proxy',
    category: 'Structural',
    description: 'Provides a surrogate or placeholder for another object to control access to it.',
    intent: 'Provide a surrogate or placeholder for another object to control access to it.',
    applicability: 'Use when you need a more versatile or sophisticated reference to an object than a simple pointer.',
    structure: 'A Proxy conforms to the Subject interface so it can be substituted for the RealSubject.',
    participants: 'Proxy, Subject, RealSubject.',
    collaborations: 'The Proxy forwards requests to the RealSubject when appropriate.',
    consequences: 'Can be used to implement lazy initialization, access control, or logging.',
    implementation: 'Implement the same interface as the real object and hold a reference to it.',
    knownUses: 'Remote proxies for network connections, virtual proxies for lazy loading, protection proxies for access control.',
    relatedPatterns: ['Adapter', 'Decorator'],
    sampleCode: '...'
  },
  // --- Behavioral Patterns ---
  {
    name: 'Chain of Responsibility',
    category: 'Behavioral',
    description: 'Avoids coupling the sender of a request to its receiver by giving more than one object a chance to handle the request.',
    intent: 'Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.',
    applicability: 'Use when more than one object may handle a request, and the handler isn\'t known a priori.',
    structure: 'A Handler defines an interface for handling requests and optionally holds a reference to a successor.',
    participants: 'Handler, ConcreteHandler, Client.',
    collaborations: 'When a client issues a request, it is passed along the chain until a ConcreteHandler takes responsibility for it.',
    consequences: 'Reduced coupling, added flexibility in assigning responsibilities to objects.',
    implementation: 'Each handler holds a reference to its successor.',
    knownUses: 'Event handling in UI toolkits, middleware in web frameworks.',
    relatedPatterns: ['Composite'],
    sampleCode: '...'
  },
  {
    name: 'Command',
    category: 'Behavioral',
    description: 'Encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.',
    intent: 'Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.',
    applicability: 'Use when you want to parameterize objects by an action to perform.',
    structure: 'A Command declares an interface for executing an operation. A ConcreteCommand binds a Receiver with an action.',
    participants: 'Command, ConcreteCommand, Client, Invoker, Receiver.',
    collaborations: 'The Invoker asks the Command to carry out the request.',
    consequences: 'Decouples the object that invokes the operation from the one that knows how to perform it.',
    implementation: 'The command object holds a reference to the receiver and invokes one or more of its methods.',
    knownUses: 'GUI buttons and menu items, transactional systems, job queues.',
    relatedPatterns: ['Composite', 'Memento', 'Prototype'],
    sampleCode: '...'
  },
  {
    name: 'Interpreter',
    category: 'Behavioral',
    description: 'Given a language, defines a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.',
    intent: 'Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.',
    applicability: 'Use when there is a language to interpret, and you can represent sentences in the language as abstract syntax trees.',
    structure: 'An AbstractExpression declares an interface for executing an operation. Terminal and Nonterminal expressions implement this interface.',
    participants: 'AbstractExpression, TerminalExpression, NonterminalExpression, Context, Client.',
    collaborations: 'The client builds (or is given) an abstract syntax tree representing a sentence in the language.',
    consequences: 'It\'s easy to change and extend the grammar.',
    implementation: 'Create a class for each terminal and nonterminal symbol in the grammar.',
    knownUses: 'SQL parsers, regular expression engines.',
    relatedPatterns: ['Composite', 'Flyweight', 'Iterator', 'Visitor'],
    sampleCode: '...'
  },
  {
    name: 'Iterator',
    category: 'Behavioral',
    description: 'Provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.',
    intent: 'Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.',
    applicability: 'Use to access an aggregate object\'s contents without exposing its internal representation.',
    structure: 'An Iterator defines an interface for accessing elements, and a ConcreteIterator implements this interface.',
    participants: 'Iterator, ConcreteIterator, Aggregate, ConcreteAggregate.',
    collaborations: 'A ConcreteIterator keeps track of the current position in the traversal of the aggregate.',
    consequences: 'Supports variations in the traversal of an aggregate.',
    implementation: 'The iterator is responsible for managing the current position in the collection.',
    knownUses: 'Standard Template Library (STL) in C++, Java Collections Framework.',
    relatedPatterns: ['Composite', 'Factory Method', 'Memento'],
    sampleCode: '...'
  },
  {
    name: 'Mediator',
    category: 'Behavioral',
    description: 'Defines an object that encapsulates how a set of objects interact.',
    intent: 'Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly.',
    applicability: 'Use when a set of objects communicate in well-defined but complex ways.',
    structure: 'A Mediator defines an interface for communicating with Colleague objects. Colleagues communicate with the Mediator.',
    participants: 'Mediator, ConcreteMediator, Colleague classes.',
    collaborations: 'Colleagues send and receive requests from a Mediator object.',
    consequences: 'Limits subclassing, decouples colleagues, simplifies object protocols.',
    implementation: 'The mediator can be implemented as an observer to coordinate updates among colleagues.',
    knownUses: 'Dialog boxes in GUI toolkits, air traffic control systems.',
    relatedPatterns: ['Observer', 'Facade'],
    sampleCode: '...'
  },
  {
    name: 'Memento',
    category: 'Behavioral',
    description: 'Without violating encapsulation, captures and externalizes an object\'s internal state so that the object can be restored to this state later.',
    intent: 'Without violating encapsulation, capture and externalize an object\'s internal state so that the object can be restored to this state later.',
    applicability: 'Use when you must save a snapshot of an object\'s state to be able to restore it later, and a direct interface to obtaining the state would expose implementation details.',
    structure: 'An Originator creates a Memento containing a snapshot of its internal state. A Caretaker is responsible for the memento\'s safekeeping.',
    participants: 'Memento, Originator, Caretaker.',
    collaborations: 'A caretaker requests a memento from an originator, holds it for a time, and passes it back to the originator.',
    consequences: 'Preserves encapsulation boundaries, simplifies the originator.',
    implementation: 'The memento can be implemented to have two interfaces: a wide one for the originator and a narrow one for other objects.',
    knownUses: 'Undo/redo mechanisms in software applications.',
    relatedPatterns: ['Command', 'Iterator'],
    sampleCode: '...'
  },
  {
    name: 'Observer',
    category: 'Behavioral',
    description: 'Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.',
    intent: 'Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.',
    applicability: 'Use when a change to one object requires changing others, and you don\'t know how many objects need to be changed.',
    structure: 'A Subject maintains a list of its dependents, called Observers, and notifies them automatically of any state changes.',
    participants: 'Subject, Observer, ConcreteSubject, ConcreteObserver.',
    collaborations: 'The ConcreteSubject notifies its observers whenever a change occurs.',
    consequences: 'Abstract coupling between Subject and Observer, support for broadcast communication.',
    implementation: 'The subject maintains a list of observers and has methods to attach and detach them.',
    knownUses: 'Model-View-Controller (MVC) architectural pattern, event listeners in GUIs.',
    relatedPatterns: ['Mediator', 'Singleton'],
    sampleCode: '...'
  },
  {
    name: 'State',
    category: 'Behavioral',
    description: 'Allows an object to alter its behavior when its internal state changes. The object will appear to change its class.',
    intent: 'Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.',
    applicability: 'Use when an object\'s behavior depends on its state, and it must change its behavior at run-time depending on that state.',
    structure: 'A Context delegates state-specific requests to the current ConcreteState object.',
    participants: 'Context, State, ConcreteState.',
    collaborations: 'The Context delegates state-specific requests to the current ConcreteState object.',
    consequences: 'Localizes state-specific behavior and partitions behavior for different states.',
    implementation: 'The context holds a reference to a state object, which can be replaced at runtime.',
    knownUses: 'TCP connection states, GUI widget states.',
    relatedPatterns: ['Flyweight', 'Strategy'],
    sampleCode: '...'
  },
  {
    name: 'Strategy',
    category: 'Behavioral',
    description: 'Defines a family of algorithms, encapsulates each one, and makes them interchangeable.',
    intent: 'Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.',
    applicability: 'Use when you have many related classes that differ only in their behavior.',
    structure: 'A Context is configured with a ConcreteStrategy object.',
    participants: 'Strategy, ConcreteStrategy, Context.',
    collaborations: 'The Context delegates some work to the Strategy object.',
    consequences: 'An alternative to subclassing, avoids conditional statements.',
    implementation: 'The context holds a reference to a strategy object, which can be changed at runtime.',
    knownUses: 'Validation, sorting, and other algorithms.',
    relatedPatterns: ['Flyweight', 'State'],
    sampleCode: '...'
  },
  {
    name: 'Template Method',
    category: 'Behavioral',
    description: 'Defines the skeleton of an algorithm in an operation, deferring some steps to subclasses.',
    intent: 'Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm\'s structure.',
    applicability: 'Use to implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary.',
    structure: 'An AbstractClass defines a template method that calls primitive operations. ConcreteClasses implement the primitive operations.',
    participants: 'AbstractClass, ConcreteClass.',
    collaborations: 'The template method in the AbstractClass calls the primitive operations implemented by the ConcreteClass.',
    consequences: 'A fundamental technique for code reuse.',
    implementation: 'The template method is a method in a superclass, which can be non-abstract.',
    knownUses: 'Frameworks of all kinds.',
    relatedPatterns: ['Factory Method', 'Strategy'],
    sampleCode: '...'
  },
  {
    name: 'Visitor',
    category: 'Behavioral',
    description: 'Represents an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.',
    intent: 'Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.',
    applicability: 'Use when you have many distinct and unrelated operations to perform on objects in a class hierarchy.',
    structure: 'A Visitor declares a Visit operation for each class of ConcreteElement in the object structure.',
    participants: 'Visitor, ConcreteVisitor, Element, ConcreteElement, ObjectStructure.',
    collaborations: 'A client that uses the Visitor pattern must create a ConcreteVisitor object and then traverse the object structure, visiting each element with the visitor.',
    consequences: 'Makes adding new operations easy, but adding new ConcreteElement classes is hard.',
    implementation: 'Each element class provides an `accept` method that takes a visitor as an argument.',
    knownUses: 'Compiler operations, such as type checking and code generation.',
    relatedPatterns: ['Composite', 'Interpreter'],
    sampleCode: '...'
  }
];

// 清空并重新插入所有设计模式
db.patterns.drop();
db.createCollection('patterns');
db.patterns.insertMany(patterns);
print(`Inserted ${db.patterns.countDocuments()} patterns.`);


// --- 挑战数据 ---
// 清空挑战
db.challenges.drop();
db.createCollection('challenges');

const allPatterns = db.patterns.find().toArray();
const challenges = [];

allPatterns.forEach(pattern => {
  // 为每个设计模式创建初级挑战
  challenges.push({
    title: `Implement a basic ${pattern.name} pattern`,
    description: `Create a simple implementation of the ${pattern.name} pattern.`,
    pattern: pattern._id,
    level: 'beginner',
    scenario: `You are tasked with a simple scenario that can be solved using the ${pattern.name} pattern.`,
    requirements: [
      `Implement the core components of the ${pattern.name} pattern.`,
      `The solution should demonstrate the main intent of the ${pattern.name} pattern.`
    ],
    hints: [
      `Review the structure of the ${pattern.name} pattern.`,
      `Focus on the roles of the main participants in the ${pattern.name} pattern.`
    ],
    sampleSolution: '// Basic implementation code here',
    testCases: [],
    timeLimit: 1800,
    difficulty: 2,
    tags: [pattern.name.toLowerCase().replace(' ', '-'), 'beginner', pattern.category.toLowerCase()]
  });
  
  // 为每个设计模式创建中级挑战
  challenges.push({
    title: `Implement an intermediate ${pattern.name} pattern`,
    description: `Create a more complex implementation of the ${pattern.name} pattern with additional features.`,
    pattern: pattern._id,
    level: 'intermediate',
    scenario: `You are working on a real-world application that requires a robust implementation of the ${pattern.name} pattern.`,
    requirements: [
      `Implement a complete ${pattern.name} pattern with all core components.`,
      `Add error handling and edge case management.`,
      `Ensure the implementation follows best practices for the ${pattern.name} pattern.`
    ],
    hints: [
      `Consider how the ${pattern.name} pattern interacts with other components in a larger system.`,
      `Think about potential issues that might arise in a production environment.`
    ],
    sampleSolution: '// Intermediate implementation code here',
    testCases: [],
    timeLimit: 2400,
    difficulty: 5,
    tags: [pattern.name.toLowerCase().replace(' ', '-'), 'intermediate', pattern.category.toLowerCase()]
  });
  
  // 为每个设计模式创建高级挑战
  challenges.push({
    title: `Master the ${pattern.name} pattern`,
    description: `Create an advanced implementation of the ${pattern.name} pattern that demonstrates expert understanding.`,
    pattern: pattern._id,
    level: 'advanced',
    scenario: `You are designing a complex enterprise system where the ${pattern.name} pattern must be implemented with maximum flexibility and scalability.`,
    requirements: [
      `Implement an advanced version of the ${pattern.name} pattern that can handle complex scenarios.`,
      `Optimize the implementation for performance and maintainability.`,
      `Demonstrate how this pattern can be combined with other patterns to solve complex problems.`
    ],
    hints: [
      `Consider how to make your implementation extensible for future requirements.`,
      `Think about potential trade-offs and how to mitigate them.`,
      `Explore advanced features of the ${pattern.name} pattern not commonly used.`
    ],
    sampleSolution: '// Advanced implementation code here',
    testCases: [],
    timeLimit: 3600,
    difficulty: 8,
    tags: [pattern.name.toLowerCase().replace(' ', '-'), 'advanced', pattern.category.toLowerCase()]
  });
});

db.challenges.insertMany(challenges);
print(`Inserted ${db.challenges.countDocuments()} challenges.`);


// --- 用户数据 ---
// 仅在测试用户不存在时插入
const testUserExists = db.users.findOne({ email: 'test@example.com' });
if (!testUserExists) {
  db.users.insertOne({
    username: 'testuser',
    email: 'test@example.com',
    password: '$2a$10$X/HsX3wnMqb3UUL9UHjbUO9RGQJnJ0JjbEiuH9.YV5xSE/2EiEMqm', // 'password'
    firstName: 'Test',
    lastName: 'User',
    role: 'user',
    createdAt: new Date(),
    progress: {
      currentLevel: 'beginner',
      currentPattern: null,
      completedPatterns: {
        beginner: [],
        intermediate: [],
        advanced: []
      }
    },
    preferences: {
      theme: 'light',
      aiProvider: 'openai',
      notifications: {
        email: true,
        push: true
      }
    }
  });
  print('Inserted test user.');
} else {
  print('Test user already exists.');
}


// --- 进度集合 ---
db.createCollection('progress');
print('Collection "progress" is ready.');

print('MongoDB initialization script finished!'); 